package me.android.library.common.viewmodel;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import lombok.Getter;
import mylab.utils.common.concurrent.RunnableUtil;

@Getter
public class GenericViewModel<T> extends ViewModel {
    private final MutableLiveData<T> data = new MutableLiveData<>();
    private final MutableLiveData<Boolean> loading = new MutableLiveData<>(false);
    private final MutableLiveData<Throwable> error = new MutableLiveData<>();

    public T getValue() {
        return data.getValue();
    }

    public boolean isLoading() {
        if (loading.getValue() != null) {
            return loading.getValue();
        }
        return false;
    }

    public Throwable getThrowable() {
        if (error.getValue() != null) {
            return error.getValue();
        }
        return null;
    }


    // 设置数据
    public void setData(T newData) {
        loading.setValue(false);
        error.setValue(null);
        data.setValue(newData);
    }

    // 设置加载状态
    public void setLoading(boolean isLoading) {
        loading.setValue(isLoading);
    }

    // 设置错误
    public void setError(Throwable throwable) {
        loading.setValue(false);
        error.setValue(throwable);
    }

    // 在后台线程执行任务
    protected void executeAsync(Runnable task) {
        RunnableUtil.submit(() -> {
            loading.postValue(true);
            error.postValue(null);
            try {
                task.run();
            } catch (Exception e) {
                error.postValue(e);
            } finally {
                loading.postValue(false);
            }
        });
    }
}